<template>
  <div class="max-w-48 relative mx-auto header-search rounded-2xl"
    ref="search">
    <div class="flex items-stretch rounded-lg">
      <div class="flex-1 relative">
        <input type="text"
          v-model="tag"
          name="toolifySearch"
          class="w-full h-8 text-sm px-4  text-gray-1000 placeholder-gray-1900 outline-none border-white border-transparent focus:outline-none rounded-l-2xl"
          @keyup.enter="toPageSearch()"
          @focus="initOptions()"
          :placeholder="$t('index_header_searchPlacegolder')" />
        <!-- <div class="cursor-pointer absolute top-1 right-2 h-6 px-2 flex items-center leading-none text-sm border border-gray-100 rounded"
          :class="{'text-white border-white bg-purple-1300 hover:opacity-90': useAi,'text-red-500 bg-white border-red-500 hover:border-purple-1300 hover:text-purple-1300 noUse': !useAi}"
          @click="aiUse">
          {{$t('index_banner_byAi')}}
        </div> -->
      </div>
      <div class="flex-shrink-0 h-8 px-3 flex items-center bg-purple-1300 hover:opacity-90 rounded-r-2xl cursor-pointer"
        @click="toPageSearch()">
        <span class="block w-3.5 h-3.5">
          <svg-icon className="block flex-shrink-0 text-white text-xs w-3.5 h-3.5"
            iconName='search_white'></svg-icon>
        </span>
      </div>
    </div>

    <div class="search-result bg-white absolute top-8 left-1/2 right-0 rounded-lg z-10"
      v-if="visible">
      <virtual-list style="max-height: 400px; overflow-y: auto;"
        v-if="listsOption && listsOption.length >0"
        ref="virtual"
        :data-key="'id'"
        :keeps="15"
        :data-sources="listsOption"
        :data-component="itemComponent"
        :extra-props="{}" />
      <div class="w-2/4 mx-auto pb-4 text-center"
        v-if="searchLoading || (isSearching && listsOption.length === 1)">
        <el-button type="text"
          class="cursor-default">
          <img src="@/static/images/loading.png"
            class="loading"
            alt=""
            srcset="">
        </el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState, mapMutations } from 'vuex'
import SearchItemNew from '~/components/SearchItemNew.vue'
import VirtualList from 'vue-virtual-scroll-list'
import search from '~/mixins/search'
export default {
  name: 'CommonHeaderSearch',
  components: { VirtualList },
  mixins: [search],
  data() {
    return {
      visible: false,
      tag: null,
      timer: null,
      isSearching: false,

      listsOption: [],
      categoriesList: [],
      toolsList: [],

      itemComponent: SearchItemNew,

      useAi: true,
    }
  },
  computed: {
    ...mapState({
      locale: (state) => state.locale,
      searchTools: (state) => state.searchTools,
      searchCategory: (state) => state.searchCategory,
      searchLoading: (state) => state.searchLoading,
    }),
  },
  watch: {
    tag: {
      handler() {
        this.initOptions()
      },
      deep: true,
      immediate: true,
    },
    useAi: {
      handler() {
        this.initOptions()
      },
      deep: true,
      immediate: true,
    },
  },
  created() {
    /* if (
      this.$route.query.useAi &&
      typeof this.$route.query.useAi === 'string'
    ) {
      if (parseInt(this.$route.query.useAi) === 1) {
        this.useAi = true
      } else if (parseInt(this.$route.query.useAi) === 2) {
        this.useAi = false
      }
    } */
  },
  mounted() {
    document.addEventListener('click', this.handleClick)
  },
  methods: {
    handleClick(event) {
      if (this.$refs.search) {
        let self = this.$refs.search.contains(event.target)
        if (!self) {
          this.visible = false
        }
      }
    },
    initOptions() {
      if (this.hasRealVal(this.tag)) {
        this.visible = true
      } else {
        this.visible = false
      }

      if (this.timer) {
        clearTimeout(this.timer)
      }

      this.isSearching = true

      this.listsOption = []

      /* this.timer = setTimeout(() => { */
      if (this.tag) {
        this.listsOption.push({
          type: 'searchFor',
          tag: this.tag,
          id: 'searchFor',
          useAi: this.useAi,
        })
      }

      /* 搜索分类 */
      let categoriesList = []
      let tag
      if (this.hasRealVal(this.tag)) {
        tag = this.tag.toLowerCase()
      }
      if (
        this.searchCategory &&
        this.searchCategory.length > 0 &&
        this.hasRealVal(this.tag)
      ) {
        this.searchCategory.forEach((item, key) => {
          if (typeof this.tag === 'string' && typeof item.n === 'string') {
            if (item.n.toLowerCase() === tag) {
              categoriesList.unshift({
                ...item,
                type: 'category',
                id: `category-${key}`,
                isMatch: true,
                tag: this.tag,
              })
            } else if (item.n.toLowerCase().indexOf(tag) >= 0) {
              categoriesList.push({
                ...item,
                type: 'category',
                id: `category-${key}`,
                tag: this.tag,
              })
            }
          }
        })
      }

      if (categoriesList && categoriesList.length > 0) {
        this.listsOption.push(
          {
            type: 'categories',
            num: categoriesList.length,
            id: 'categories',
            tag: this.tag,
          },
          ...categoriesList
        )
      }
      this.categoriesList = JSON.parse(JSON.stringify(categoriesList))
      /* 搜索分类 end */

      /* 搜索工具 */
      let toolsList = []
      if (
        this.searchTools &&
        this.searchTools.length > 0 &&
        this.hasRealVal(this.tag)
      ) {
        this.searchTools.forEach((item, key) => {
          if (typeof this.tag === 'string' && typeof item.n === 'string') {
            if (item.n.toLowerCase() === tag) {
              toolsList.unshift({
                ...item,
                type: 'tool',
                id: `tool-${key}`,
                isMatch: true,
                tag: this.tag,
              })
            } else if (
              item.n.toLowerCase().indexOf(tag) >= 0
            ) {
              toolsList.push({
                ...item,
                type: 'tool',
                id: `tool-${key}`,
                tag: this.tag,
              })
            }
          }
        })
      }
      if (toolsList && toolsList.length > 0) {
        this.listsOption.push(
          {
            type: 'tools',
            num: toolsList.length,
            id: 'tools',
            tag: this.tag,
          },
          ...toolsList
        )
      }

      this.toolsList = JSON.parse(JSON.stringify(toolsList))
      /* 搜索工具 end */

      /* total */
      if (
        (categoriesList && categoriesList.length > 0) ||
        (toolsList && toolsList.length > 0)
      ) {
        this.listsOption.push({
          type: 'total',
          num: categoriesList.length + toolsList.length,
          id: 'total',
        })
      }
      /* total end */

      this.isSearching = false
      /* }, 30) */
    },
    toPageSearch() {
      this.visible = false
      if (this.hasRealVal(this.tag)) {
        if (
          this.categoriesList &&
          this.categoriesList.length > 0 &&
          this.categoriesList[0].isMatch
        ) {
          this.searchStatistics(
            `https://www.toolify.ai${
              this.locale === 'en' ? '' : `/${this.locale}`
            }/category/${this.categoriesList[0].h}`,
            this.tag,
            0
          )
          /* this.$router.push({
            name:
              this.locale === 'en' ? 'category-handle' : 'lang-category-handle',
            params: {
              lang: this.locale,
              handle: this.categoriesList[0].h,
            },
          }) */
          const routeData = this.$router.resolve({
            name:
              this.locale === 'en' ? 'category-handle' : 'lang-category-handle',
            params: {
              lang: this.locale,
              handle: this.categoriesList[0].h,
            },
          })
          window.open(routeData.href, '_blank')
        } else if (
          this.toolsList &&
          this.toolsList.length > 0 &&
          this.toolsList[0].isMatch
        ) {
          this.searchStatistics(
            `https://www.toolify.ai${
              this.locale === 'en' ? '' : `/${this.locale}`
            }/tool/${this.toolsList[0].h}`,
            this.tag,
            0
          )
          /* this.$router.push({
            name: this.locale === 'en' ? 'tool-handle' : 'lang-tool-handle',
            params: {
              lang: this.locale,
              handle: this.toolsList[0].h,
            },
          }) */

          const routeData = this.$router.resolve({
            name: this.locale === 'en' ? 'tool-handle' : 'lang-tool-handle',
            params: {
              lang: this.locale,
              handle: this.toolsList[0].h,
            },
          })
          window.open(routeData.href, '_blank')
        } else {
          /* this.$router.push({
            name: this.locale === 'en' ? 'search-handle' : 'lang-search-handle',
            params: {
              lang: this.locale,
              handle: encodeURIComponent(this.tag),
            },
          }) */
          const routeData = this.$router.resolve({
            name: this.locale === 'en' ? 'search-handle' : 'lang-search-handle',
            params: {
              lang: this.locale,
              handle: encodeURIComponent(this.tag),
            },
            query: {
              r: this.$route.name.replace('lang-', ''),
              /* useAi: this.useAi ? 1 : 2, */
            },
          })
          window.open(routeData.href, '_blank')
        }
      }
    },
    aiUse() {
      this.useAi = !this.useAi
    },
  },
  beforeDestroy() {
    document.removeEventListener('click', this.handleClick)
  },
}
</script>
<style lang='scss' scoped>
.header-search {
  .search-result {
    width: 400px;
    max-width: 95vw;
    transform: translateX(-50%);
    box-shadow: 0px 0px 8px 0px rgba(0, 0, 0, 0.1);
  }
  .noUse {
    position: relative;
    &:not(:hover) {
      &::before {
        position: absolute;
        content: ' ';
        height: 100%;
        width: 100%;
        background: linear-gradient(
          to top right,
          rgba(0, 0, 0, 0),
          rgba(0, 0, 0, 0) 48%,
          #ef4444,
          rgba(0, 0, 0, 0) 51%,
          rgba(0, 0, 0, 0)
        );
        left: 0;
        top: 0;
      }
    }
  }
}
</style>
